package net.guerlab.ali.dayu;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 回复响应消息对象
 * 
 * @author guer
 *
 */
public class Result {

    /**
     * 响应码
     */
    private String code;

    /**
     * 响应内容
     */
    private String model;

    /**
     * 是否成功
     */
    private boolean success;

    /**
     * 响应信息
     */
    private String msg;

    /**
     * 获取响应码
     * 
     * @return 响应码
     */
    public final String getCode() {
        return code == null ? "" : code;
    }

    /**
     * 获取响应内容
     * 
     * @return 响应内容
     */
    public final String getModel() {
        return model == null ? "" : model;
    }

    /**
     * 获取是否成功
     * 
     * @return 是否成功
     */
    public final boolean isSuccess() {
        return success;
    }

    /**
     * 获取响应信息
     * 
     * @return 响应信息
     */
    public final String getMsg() {
        return msg == null ? "" : msg;
    }

    @Override
    public String toString() {
        return "Result [code=" + code + ", model=" + model + ", success=" + success + ", msg=" + msg + "]";
    }

    /**
     * 解析json字符串内容生成响应对象
     * 
     * @param data
     *            json字符串内容
     * @return 响应对象
     */
    static final Result parse(String data) {
        if (StringUtils.isBlank(data)) {
            return null;
        }

        JSONObject object = null;

        try {
            object = JSONObject.parseObject(data);
        } catch (Exception e) {
            return null;
        }

        Result result = new Result();
        if (object.containsKey("errorCode")) {
            result.code = object.getString("errorCode");
        } else {
            result.code = object.getString("code");
        }
        if (object.containsKey("model")) {
            result.model = object.getString("model");
        }
        if (object.containsKey("success")) {
            result.success = object.getBoolean("success").booleanValue();
        }
        if (object.containsKey("errorMessage")) {
            result.msg = object.getString("errorMessage");
        } else if (object.containsKey("msg")) {
            result.msg = object.getString("msg");
        }

        return result;
    }
}
